package com.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

object GsonUtil {

    val gson = Gson()

    fun toJson(obj: Any?): String? {
        return try {
            gson.toJson(obj)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            ""
        }
    }
    inline fun <reified T:Any> toJsonByType(obj: Any?): String? {
        return try {
            gson.toJson(obj, object : TypeToken<T>() {}.type)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            ""
        }
    }

    inline fun <reified T : Any> fromJson(str: String?, cls: Class<T>?): T? {
        try {
            return gson.fromJson<T>(str, cls)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return null
    }


    inline fun <reified T : Any> gsonSafeParse(jsonString: String?): T?  {
        return try {
            gson.fromJson(jsonString, T::class.java)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 安全的转换集合类型
     */
    inline fun <reified T : Any> gsonSafeParseCollection(jsonString: String?): T? {
        return try {
            gson.fromJson<T>(jsonString, object : TypeToken<T>() {}.type)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

}